import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * User: 12629
 * Date: 2021/11/17
 * Time: 9:28
 * Description:
 * 创建对象的方式：
 * 1、new
 * 2、clone()
 * 3、Class的newInstance()
 * 4、Constructord的newInstance();
 * 5、
 * 6、
 */
public class ReflectClassDemo {
    public static void reflectNewInstance() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Class<?> c1 = Class.forName("Student");
        Student student = (Student)c1.newInstance();
        System.out.println(student);
    }

    public static void reflectPrivateMethond() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Class<?> c1 = Class.forName("Student");
        Student student = (Student)c1.newInstance();

        try {
            Method method = c1.getDeclaredMethod("function",String.class);
            method.setAccessible(true);//
            method.invoke(student,"我是这个对象function的方法的参数");

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }


    public static void reflectPrivateConstructor() {
        try {
            Class<?> c1 = Class.forName("Student");
            Constructor<?> constructor = c1.getDeclaredConstructor(String.class,int.class);
            constructor.setAccessible(true);

            Student student = (Student)constructor.newInstance("zhangsan",98);

            System.out.println(student);

        } catch (ClassNotFoundException | NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public static void reflectPrivateField() {
        try {
            Class<?> c1 = Class.forName("Student");
            Field field = c1.getDeclaredField("name");
            field.setAccessible(true);

            Student student = (Student)c1.newInstance();

            field.set(student,"lisi");

            System.out.println(field.get(student));

            System.out.println(student);


        } catch (ClassNotFoundException | NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

    }


    public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        reflectPrivateField();
        //reflectPrivateConstructor();
        //reflectNewInstance();
        //reflectPrivateMethond();
    }
}
